package com.ego.service.impl;

import com.ego.service.UploadService;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.List;

/**
 * @author Ares
 * @date 2020-11-23
 */
@Service
@Slf4j
public class UploadServiceImpl implements UploadService {

    private static final List<String> SUFFIXES = Arrays.asList("image/png", "image/jpeg");

    @Resource
    private FastFileStorageClient client;
    @Override
    public String upload(MultipartFile file) {
        try {
            // 1、图片信息校验
            // 1)校验文件类型
            String type = file.getContentType();
            if (!SUFFIXES.contains(type)) {
                log.info("上传失败，文件类型不匹配：{}", type);
                return null;
            }
            // 2)校验图片内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                log.info("上传失败，文件内容不符合要求");
                return null;
            }
            // 2、保存图片
            // 2.1、生成保存目录
            // File dir = new File("D:\\img");
            String filename = file.getOriginalFilename();
            assert filename != null;
            String etx = filename.substring(filename.lastIndexOf("."));
            StorePath storePath = client.uploadFile(file.getInputStream(), file.getSize(), etx, null);
            String path = storePath.getFullPath();
            // 2.3、拼接图片地址
            return "http://image.ego.com/" + path;
        } catch (Exception e) {
            return null;
        }
    }
}
